package com.xiashitech.agent.rule.usermatch.inst;

import com.google.auto.service.AutoService;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.redis.RedisData;
import com.xiashitech.agent.rule.usermatch.base.UserInfoMatchRule;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import ognl.Ognl;

import java.util.Date;
import java.util.List;

//@AutoService(UserInfoMatchRule.class)
public class XSRedisResponseUserMatch<REQUEST> implements UserInfoMatchRule<REQUEST> {
    @Override
    public UserRequest extractUserInfo(REQUEST request) {
        if (request == null || !(request instanceof RedisData)) {
            return UserRequest.builder().build();
        }
        UserRequest userRequest = UserRequest.builder().requestDate(String.valueOf(new Date().getTime())).build();
        try {
            RedisData redisData = (RedisData)request;
            if(redisData == null) {
                return UserRequest.builder().build();
            }
            Object redisValueObj = JsonUtil.getObjectFromByteArray(redisData.getValue());
            if(redisValueObj != null && List.class.isAssignableFrom(redisValueObj.getClass())) {
                List<Object> value = (List<Object>) redisValueObj;
                for (Object item : value) { // 针对 永达汽车 ECM 系统的
                    if (item.getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")) {
                        Object authentication = item;
                        Object principal = authentication.getClass().getMethod("getPrincipal").invoke(authentication);
                        if (principal != null) {
                            if(principal.getClass() == String.class)
                                userRequest.setUserid((String) principal);
                            else { // 永达汽车不会进入这分支
                                String userIdPath = AgentConfigDTO.getConfig().getUseridpath().get(StartConfig.getParamValueFromKey(StartConfig.systemId));
                                String userId = String.valueOf(Ognl.getValue(userIdPath, principal));
                                userRequest.setUserid(userId);
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return userRequest;
    }

    @Override
    public Integer getOrder() {
        return 8;
    }
}
